package com.Common.Shiro;

import com.Mapper.Admin.MenuMapper;
import com.Mapper.Admin.RoleMapper;
import com.Model.Admin.Menu;
import com.Model.Admin.Role;
import com.Model.Admin.UserInfo;
import com.Service.Admin.UserInfoService;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description:
 * @Author: suzr
 * @Date: 2019-7-22 14:11
 * @return:
 * @throws:
 */
public class CustomRealm extends AuthorizingRealm {
    private static final Logger log = LoggerFactory.getLogger(CustomRealm.class);

    private static final long sessionKeyTimeOut = 3600_000L;

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;

    //授权权限信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        UserInfo userInfo = (UserInfo) principalCollection.getPrimaryPrincipal();

        for (Role role : userInfo.getRoleList()) {
            authorizationInfo.addRole(role.getRoleName());
            for (Menu m : userInfo.getMenuList()) {
                authorizationInfo.addStringPermission(m.getMenuId());
            }

        }
        // for (SysRole)
       /*String userName=(String)principalCollection.getPrimaryPrincipal();
       //查询拥有的权限
        List<menu> lst= menuMappers.getMenuByUser(userName);
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermission("");
        return simpleAuthorizationInfo;*/
        return authorizationInfo;
    }


    //认证-登陆 身份认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String ueserName = token.getUsername();
        String password = String.valueOf(token.getPassword());
        log.info("当前登陆用户名={}密码={}", ueserName, password);
        UserInfo user = userInfoService.getUserInfo(ueserName, password);
        List<Role> roleInfo = roleMapper.getRoleInfoByUserName(ueserName);
        List<Menu> menus = menuMapper.getMenuByUser(ueserName);
        if (user == null) {
            throw new UnknownAccountException("用户名不存在！");
        }
        if (!user.getPassword().equals(password)) {
            throw new UnknownAccountException("用户密码不匹配！");
        }
        user.setRoleList(roleInfo);
        user.setMenuList(menus);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,
                user.getPassword(),
                ByteSource.Util.bytes("shiro.encrypt.password.salt"),
                getName()
        );
        setSession("uid", user.getUserId());

        return info;
    }

    /**
     * 将key 对应value 放入shiro 的session中 交给httpSession管理
     *
     * @param key
     * @param value
     */
    private void setSession(String key, Object value) {
        Session session = SecurityUtils.getSubject().getSession();
        if (session != null) {
            session.setAttribute(key, value);
            session.setTimeout(sessionKeyTimeOut);
        }
    }
}
